#include<stdio.h>
#include<assert.h>
#include<malloc.h>
#include<stdlib.h>

typedef int SLDataType;

typedef struct SeqList{
  SLDataType* a;//指向顺序表的指针
  int size;//元素个数
  int capacity;//容量
}SeqList;

//初始化函数
void SeqListInit(SeqList* ps)
{
  assert(ps);
  ps->size = 0;
  ps->capacity = 0;
  ps->a = NULL;
}

//销毁顺序表
void SeqListDestory(SeqList* ps)
{
  assert(ps);
  free(ps->a);//释放顺序表指针指向的空间
  ps->a = NULL;
  ps->size = 0;
  ps->capacity = 0;
}

//打印顺序表
void SeqListPrint(SeqList* ps)
{
  assert(ps);
  int i = 0;
  for(i=0;i<ps->size;i++)
  {
    printf("%d ",(ps->a)[i]);
  }
  printf("\n");
}

//检查顺序表是否满
void SeqCheckCapacity(SeqList* ps)
{
  assert(ps);
  int newcapacity = 0;
  SLDataType* newA = NULL;
  if(ps->capacity==ps->size)//满了
  {
    newcapacity = ps->capacity==0?4:(2*ps->capacity);
    newA = (SLDataType*)realloc(ps->a, newcapacity*sizeof(SLDataType));//若传入realloc的指针为空指针(NULL)，则realloc函数的作用相当于malloc函数。
    if(newA==NULL)
    {
      printf("realloc fail\n");
      exit(-1);
    }  
  
   ps->a = newA;
   ps->capacity = newcapacity; 

  }
}
//尾插
void SeqListPushBack(SeqList* ps,SLDataType x)
{
  assert(ps);
  SeqCheckCapacity(ps);
  (ps->a)[ps->size] = x;
  ps->size++;
}

//头插
void SeqListPushFront(SeqList* ps,SLDataType x)
{
  assert(ps);
  int i= 0;
  SeqCheckCapacity(ps);
  for(i=ps->size;i>0;i--)
  {
    (ps->a)[i]=(ps->a)[i-1];
  }
  (ps->a)[0] = x;
  ps->size++;
}
//指定下表插入
void SeqListInsert(SeqList* ps,int pos,SLDataType x)
{
  assert(ps);
  assert(pos>=0&&pos<= ps->size);
  SeqCheckCapacity(ps);
  int i = 0;
  for(i=ps->size;i>pos;i--)
  {
    ps->a[i] = ps->a[i-1];
  }
  ps->a[pos]=x;
  ps->size++;
}
//指定下表删除
void SeqListErase(SeqList* ps,int pos)
{
  assert(ps);
  assert(ps->size>0);
  assert(pos>=0&&pos<ps->size);
  int i=0;
  for(i=pos;i<ps->size-1;i++)
  {
    ps->a[i]= ps->a[i+1];
  }
  ps->size--;

}
int main()
{
  SeqList* sq = (SeqList*)malloc(sizeof(SeqList));
  //SeqList sq;
  SeqListInit(sq);
  SeqListPushBack(sq, 1);
  SeqListPushBack(sq, 9);
  SeqListPushBack(sq, 9);
  //SeqListPushFront(sq, 9);
  //SeqListPushFront(sq, 8);
  SeqListInsert(sq,1,99);
  SeqListErase(sq,0);
  SeqListErase(sq,2);
  SeqListPrint(sq);
  SeqListDestory(sq);
  return 0;
}

















